package com.xjzd.std.concurrency;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class AlternatePrintingWithBarrier {
    private static final CyclicBarrier barrier = new CyclicBarrier(1);
    private static int number = 1;
    private static volatile boolean turn = true;

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            for (int i = 1; i <= 50; i++) {
                synchronized (AlternatePrintingWithBarrier.class) {
                    if (turn) {
                        System.out.println("Thread 1: " + number++);
                        turn = false;
                        try {
                            barrier.await();
                        } catch (InterruptedException | BrokenBarrierException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 1; i <= 50; i++) {
                synchronized (AlternatePrintingWithBarrier.class) {
                    if (!turn) {
                        System.out.println("Thread 2: " + number++);
                        turn = true;
                        try {
                            barrier.await();
                        } catch (InterruptedException | BrokenBarrierException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });

        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}